#include "NetTask.h"
#include "options.h"

void NetTask::Start()
{
	m_nWorkThreadCount = m_nStopThreadCount = 0;

	if ( g_options.bSingleThread == false )
	{
		SYSTEM_INFO si;
		::GetSystemInfo(&si);
		int32 nWorkUnitCount = si.dwNumberOfProcessors + 2;
		if ( g_options.max_workthread_count != 0 )
		{
			nWorkUnitCount = g_options.max_workthread_count;
		}

		m_pCompletePort = MyNew CompletePort();
		m_pCompletePort->start(nWorkUnitCount);

		m_vTasks.reserve(nWorkUnitCount);
		for(int i = 0;i<nWorkUnitCount;++i)
		{
			NetTaskUnit* pUnit = MyNew NetTaskUnit(this);
			pUnit->Start();
			m_vTasks.push_back(pUnit);
		}	
		Sleep(1000);
	}
	else
	{
		m_pCompletePort = MyNew CompletePort();
		m_pCompletePort->start(1);
	}
}

void NetTask::Stop()
{	
	while(m_nWorkThreadCount!=m_nStopThreadCount)
	{
		for(size_t i = 0;i<m_vTasks.size();++i)
		{
			m_pCompletePort->stop();
			m_vTasks[i]->Stop();
		}
	}

	for(size_t i = 0;i<m_vTasks.size();++i)
	{
		delete m_vTasks[i];
	}	
	
	delete m_pCompletePort;
}

void NetTask::Pool(uint32 ms)
{
	m_pCompletePort->handle(ms);
}

void NetTask::NetTaskUnit::Run()
{
	m_pTask->m_pCompletePort->handle(INFINITE);
}

void NetTask::NetTaskUnit::OnStart()
{
	::InterlockedIncrement(&m_pTask->m_nWorkThreadCount);
}

void NetTask::NetTaskUnit::OnStop()
{
	::InterlockedIncrement(&m_pTask->m_nStopThreadCount);
}

NetTask::NetTaskUnit::NetTaskUnit(NetTask* pTask)
{
	m_pTask = pTask;
}

void NetTask::Active(HANDLE h,void* obj)
{
	m_pCompletePort->active(h,obj);
}